/*
 * Copyright 2011 Alex Paréj.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.mkdir.dao;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.mkdir.model.AbstractEntitiy;

/**
 *
 * @author Alex Paréj
 */
public class AbstractDAO<T extends AbstractEntitiy> {

    @PersistenceContext
    protected EntityManager em;
    Class<T> clazz;

    public AbstractDAO(Class<T> clazz) {
        this.clazz = clazz;
    }

    public List<T> findAll() {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<T> cq = cb.createQuery(clazz);
        Root root = cq.from(clazz);
        cq.select(root);
        return em.createQuery(cq).getResultList();
    }

    public T find(Object id) {
        return em.find(clazz, id);
    }

    public void create(T object) {
        em.persist(object);
    }

    public void edit(T entity) {
        em.merge(entity);
    }

    public void edit(T[] entities) {
        for (T item : entities) {
            edit(item);
        }
    }

    public void remove(T entity) {
        em.remove(em.merge(entity));
    }

    public void remove(T[] entities) {
        for (T entity : entities) {
            remove(entity);
        }
    }
}
